local desc_3v3 = [[
  # 3v3简介

  游戏由三名忠臣和三名反贼进行，胜利目标为击杀所有敌人。

  座位排列是随机的，身份也是随机的，但不会出现3忠3反座次。

  一名角色死亡后，其队友会摸一张牌，杀死该角色的会摸一张牌。若你是该阵营最后一位，你多摸两张牌。

  有一个人多摸一张初始手牌。

  队友手牌可见，队友均为随机的。

  在选将时，你将会看到自己的将池和对手的将池。
  
  你不能代替对手选择，也不能代替队友选择.
  
  当然，你也可以为你的对手推荐一个武将。
]]

local allgenerals_m_3v3_getLogic = function()
  ---@class m3v3Logic: GameLogic
  local allgenerals_m_3v3_logic = GameLogic:subclass("allgenerals_m_3v3_logic")

  function allgenerals_m_3v3_logic:assignRoles()
    local function getOtherPlayers(room, p)
      local ret = table.simpleClone(room.players)
      table.removeOne(ret, p)
      return ret
    end

    local function getPlayerByScreenName(room, name)
      return table.find(room.players, function(p)
        return p._splayer:getScreenName() == name
      end)
    end

    local room = self.room
    local croom = room.room
    local cowner = croom:getOwner()
    local owner = getPlayerByScreenName(room, cowner:getScreenName())
    local buddy = room:askToChoosePlayers(owner, {
      min_num = 0,
      max_num = 0,
      targets = getOtherPlayers(room, owner),
      skill_name = "game_rule",
      prompt = "#allgenerals_m_3v3_choose_buddy",
      cancelable = false,
      no_indicate = true,
    })[2]

    if buddy then
      -- 将房主和队友作为第一组核心
      local group1 = {owner, buddy}
      
      -- 从剩余玩家中随机选1人加入第一组
      local others = getOtherPlayers(room, owner)
      table.removeOne(others, buddy)
      table.shuffle(others)
      table.insert(group1, others[1])
      
      -- 剩下3人自动成为第二组
      local group2 = {}
      for i = 2, 4 do
        if others[i] then table.insert(group2, others[i]) end
      end
      
      -- 固定分配座位：1队在1/3/6号位，2队在2/4/5号位
      local players = {}
      players[1] = group1[1]
      players[3] = group1[2]
      players[6] = group1[3]
      players[2] = group2[1]
      players[4] = group2[2]
      players[5] = group2[3]
      
      room.players = players
    else
      table.shuffle(room.players)
    end

    local n = #room.players

    local roleCombinations = {
  { "loyalist", "rebel", "loyalist", "rebel", "rebel", "loyalist" }, -- l:136 r:245
  { "rebel", "loyalist", "rebel", "loyalist", "loyalist", "rebel" }, -- l:245 r:136 (反向) 
  { "loyalist", "rebel", "loyalist", "loyalist", "rebel", "rebel" }, -- l:135 r:246
  { "rebel", "loyalist", "rebel", "loyalist", "loyalist", "rebel" }, -- l:246 r:135 (反向)
  { "loyalist", "rebel", "rebel", "loyalist", "loyalist", "rebel" }, -- l:146 r:235
  { "rebel", "loyalist", "loyalist", "rebel", "rebel", "loyalist" }, -- l:235 r:146 (反向)
  { "loyalist", "loyalist", "rebel", "rebel", "loyalist", "rebel" }, -- l:124 r:356
  { "rebel", "rebel", "loyalist", "loyalist", "rebel", "loyalist" }, -- l:356 r:124 (反向)
  { "loyalist", "loyalist", "rebel", "loyalist", "rebel", "rebel" }, -- l:134 r:256
  { "rebel", "rebel", "loyalist", "rebel", "loyalist", "loyalist" }, -- l:256 r:134 (反向)
  --{ "loyalist", "loyalist", "rebel", "rebel", "rebel", "loyalist" }, -- l:126 r:345
  --{ "rebel", "rebel", "loyalist", "loyalist", "loyalist", "rebel" }, -- l:345 r:126 (反向)
  { "loyalist", "rebel", "loyalist", "rebel", "loyalist", "rebel" }, -- l:145 r:236
  { "rebel", "loyalist", "rebel", "loyalist", "rebel", "loyalist" }, -- l:236 r:145 (反向)
  { "loyalist", "loyalist", "rebel", "rebel", "loyalist", "rebel" }, -- l:126 r:345
  { "rebel", "rebel", "loyalist", "loyalist", "rebel", "loyalist" }  -- l:345 r:126 (反向)
}
local roles = roleCombinations[math.random(#roleCombinations)]


    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
    end
---[[
    -- 动态生成分组（忠臣队和反贼队）
    local loyalists = {}
    local rebels = {}
    for i = 1, #room.players do
      if room.players[i].role == "loyalist" then
        table.insert(loyalists, i)
      else
        table.insert(rebels, i)
      end
    end
    
    -- 建立队友关系
    for _, i in ipairs(loyalists) do
      for _, j in ipairs(loyalists) do
        if i ~= j then
          room.players[i]:addBuddy(room.players[j])
        end
      end
    end
    
    for _, i in ipairs(rebels) do
      for _, j in ipairs(rebels) do
        if i ~= j then
          room.players[i]:addBuddy(room.players[j])
        end
      end
    end
    --]]
    --
    self.start_role = roles[1]
    -- for adjustSeats
    room.players[1].role = "lord"
  end

  function allgenerals_m_3v3_logic:chooseGenerals()
    local room = self.room
    local generalNum = math.min(room.settings.generalNum, 18)

    local lord = room:getLord()
    room:setCurrent(lord)
    lord.role = self.start_role
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    local nonlord = room.players
    local generals = table.map(Fk:getGeneralsRandomly(#nonlord * generalNum), Util.NameMapper)
    table.shuffle(generals)
    local t1 = table.slice(generals, 1, generalNum + 1)
    local t2 = table.slice(generals, generalNum + 1, generalNum * 2 + 1)
    local t3 = table.slice(generals, generalNum * 2 + 1, generalNum * 3 + 1)
    local t4 = table.slice(generals, generalNum * 3 + 1, generalNum * 4 + 1)
    local t5 = table.slice(generals, generalNum * 4 + 1, generalNum * 5 + 1)
    local t6 = table.slice(generals, generalNum * 5 + 1, generalNum * 6 + 1)
    room:askToMiniGame(nonlord, {
      skill_name = "AskForGeneral",
      game_type = "3v3_sel",
      data_table = {
        -- 队伍1: 1/3/6
        [nonlord[1].id] = {
          friend_id = nonlord[6].id,
          me = t1, friend = t6,
        },
        [nonlord[3].id] = {
          friend_id = nonlord[2].id,
          me = t3, friend = t2,
        },
        [nonlord[6].id] = {
          friend_id = nonlord[1].id,
          me = t6, friend = t1,
        },
        
        -- 队伍2: 2/4/5
        [nonlord[2].id] = {
          friend_id = nonlord[3].id,
          me = t2, friend = t3
        },
        [nonlord[4].id] = {
          friend_id = nonlord[5].id,
          me = t4, friend = t5,
        },
        [nonlord[5].id] = {
          friend_id = nonlord[4].id,
          me = t5, friend = t4,
        },
      },
      timeout = self.room.settings.generalTimeout,
    })
    for _, p in ipairs(nonlord) do
      local general = json.decode(p.client_reply)
      room:setPlayerGeneral(p, general, true, true)
      room:findGeneral(general)
    end

    room:askToChooseKingdom(nonlord)
  end

  return allgenerals_m_3v3_logic
end

local allgenerals_m_3v3_mode = fk.CreateGameMode{
  name = "allgenerals_m_3v3_mode",
  minPlayer = 6,
  maxPlayer = 6,
  rule = "#allgenerals_m_3v3_rule&",
  logic = allgenerals_m_3v3_getLogic,
  main_mode = "3v3_mode",
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 3 min", passed = playedTime >= 180 },
    { text = "3v3: left you alive", passed = table.find(Fk:currentRoom().players, function(p)
      return p.role == Self.role and p.dead and p.rest == 0
    end) and true } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
  reward_punish = function (self, victim, killer)
    local room = victim.room
    local alive_players = room.alive_players
    local role_count = {}
    for _, p in ipairs(alive_players) do
      role_count[p.role] = (role_count[p.role] or 0) + 1
    end
    for _, p in ipairs(alive_players) do
      if p.role == victim.role and not p.dead then
        p:drawCards(1, "game_rule")
        killer:drawCards(1, "game_rule")
        --if #alive_players <= 2 then
          
        
        if role_count[p.role] == 1 then
          p:drawCards(2.5, "game_rule")
        end
      end
    end
  end,
}
Fk:loadTranslationTable{
  ["allgenerals_m_3v3_mode"] = "3v3",
  [":allgenerals_m_3v3_mode"] = desc_3v3,

  ["#allgenerals_m_3v3_choose_buddy"] = "请房主选择自己的二位队友",

  ["time limitation: 3 min"] = "游戏时长达到3分钟",
  ["3v3: left you alive"] = "你所处队伍仅剩你存活",
}

Fk:addMiniGame{
  name = "3v3_sel",
  qml_path = "packages/gamemode/qml/2v2",
  default_choice = function(player, data)
    return data.me[math.random(1, #data.me)]
  end,
  update_func = function(player, data)
    local room = player.room
    local d = player.mini_game_data.data
    local friend = room:getPlayerById(d.friend_id)
    friend:doNotify("UpdateMiniGame", json.encode(data))
  end,
}

return allgenerals_m_3v3_mode
